package com.slipper.system.scheduled;

import com.slipper.common.exception.CommonException;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.slipper.PaasContext;
import com.slipper.system.api.schedule.bo.ScheduleBO;

/**
 * 定时任务工具类
 */
public class ScheduledUtil {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledUtil.class);
    
    private final static String JOB_NAME = "TASK_";

    /**
     * 获取触发器key
     */
    private static TriggerKey getTriggerKey(String jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     */
    private static JobKey getJobKey(String jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    private static CronTrigger getCronTrigger(Scheduler scheduler, String jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            logger.error("获取定时任务CronTrigger出现异常！", e);
            throw new CommonException("获取定时任务CronTrigger出现异常！", e);
        }
    }
    
    public static void createScheduleJob(ScheduleBO scheduleBO) {
        Scheduler scheduler = PaasContext.getBean(SchedulerFactoryBean.class).getScheduler();
        CronTrigger cronTrigger = ScheduledUtil.getCronTrigger(scheduler, scheduleBO.getId());
        if (cronTrigger == null) {
            ScheduledUtil.createScheduleJob(scheduler, scheduleBO);
        } else {
            ScheduledUtil.updateScheduleJob(scheduler, scheduleBO);
        }
    }

    /**
     * 创建定时任务
     */
    private static void createScheduleJob(Scheduler scheduler, ScheduleBO scheduleBO) {
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class)
                    .withIdentity(getJobKey(scheduleBO.getId()))
                    .build();

            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(scheduleBO.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(getTriggerKey(scheduleBO.getId()))
                    .withSchedule(scheduleBuilder).build();

            // 放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(ScheduledJob.JOB_PARAM_KEY, scheduleBO);

            scheduler.scheduleJob(jobDetail, trigger);

            // 暂停任务
            if (ScheduleBO.STATUS_PAUSE.equals(scheduleBO.getStatus())) {
                pauseJob(scheduleBO.getId());
            }
            
            logger.info("创建定时任务成功: {}", scheduleBO);
        } catch (SchedulerException e) {
            logger.error("创建定时任务失败: " + scheduleBO, e);
            throw new CommonException("创建定时任务失败！", e);
        }
    }

    /**
     * 更新定时任务
     */
    private static void updateScheduleJob(Scheduler scheduler, ScheduleBO scheduleBO) {
        try {
            TriggerKey triggerKey = getTriggerKey(scheduleBO.getId());

            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                    .cronSchedule(scheduleBO.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, scheduleBO.getId());

            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();

            // 参数
            trigger.getJobDataMap().put(ScheduledJob.JOB_PARAM_KEY, scheduleBO);

            scheduler.rescheduleJob(triggerKey, trigger);

            // 暂停任务
            if (ScheduleBO.STATUS_PAUSE.equals(scheduleBO.getStatus())) {
                pauseJob(scheduleBO.getId());
            }

            logger.info("更新定时任务成功: {}", scheduleBO);
        } catch (SchedulerException e) {
            logger.error("更新定时任务失败: " + scheduleBO, e);
            throw new CommonException("更新定时任务失败！", e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(ScheduleBO scheduleBO) {
        try {
            logger.info("开始执行定时任务：{}", scheduleBO);
            Scheduler scheduler = PaasContext.getBean(SchedulerFactoryBean.class).getScheduler();
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(ScheduledJob.JOB_PARAM_KEY, scheduleBO);

            scheduler.triggerJob(getJobKey(scheduleBO.getId()), dataMap);
            logger.info("定时任务调度成功：{}", scheduleBO);
        } catch (SchedulerException e) {
            logger.error("立即执行定时任务失败: " + scheduleBO, e);
            throw new CommonException("立即执行定时任务失败！", e);
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(String jobId) {
        try {
            Scheduler scheduler = PaasContext.getBean(SchedulerFactoryBean.class).getScheduler();
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            logger.error("暂停定时任务失败！", e);
            throw new CommonException("暂停定时任务失败！", e);
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(String jobId) {
        try {
            Scheduler scheduler = PaasContext.getBean(SchedulerFactoryBean.class).getScheduler();
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            logger.error("恢复定时任务失败！", e);
            throw new CommonException("恢复定时任务失败", e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(String jobId) {
        try {
            Scheduler scheduler = PaasContext.getBean(SchedulerFactoryBean.class).getScheduler();
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            logger.error("删除定时任务失败！", e);
            throw new CommonException("删除定时任务失败！", e);
        }
    }
}
